import errorCode from '@/const/errorCode'
import useConfigStore from '@/stores/config'
import useUserStore from '@/stores/user'
import axios from 'axios'
// import NProgress from 'nprogress'
import tMapKey from '@/const/t-map'
import router from '@/router'
import { removeCookie } from './cookie'
import { confirm, shake } from './util'
import { Modal } from 'ant-design-vue'
import { message } from 'ant-design-vue'

let messageInstance: any = null

function createRequest(uri: string) {
    const service = axios.create({
        baseURL: uri,
        timeout: 60000
    })

    // 请求拦截器
    service.interceptors.request.use(
        (config) => {
            // console.log(config.url, '=== config1111 ==')
            if (config.url?.startsWith('/ws')) {
                if (!config.params) {
                    config.params = {}
                }
                config.params.key = tMapKey
            }
            if (!config.headers) {
                throw new Error('错误信息')
            }
            const user = useUserStore()
            const configStore = useConfigStore()
            if (!config.headers.Authorization && user.token) {
                // console.log(user.tenantId, '=== user.tenantId111 ==');
                (config.headers as any).Authorization = user.token
            }
            if (!config.headers.notLoading) {
                configStore.updateRequestLoading(1)
            }
            return config
        },
        (error: any) => {
            return Promise.reject(error)
        }
    )

    // 响应拦截器
    service.interceptors.response.use(
        async (response) => {
            // 获取导出流文件时的文件名
            if (response.headers['download-filename']) {
                const configStore = useConfigStore()
                configStore.setDownLoadFileName(decodeURIComponent(response.headers['download-filename']))
            }
            // NProgress.done()
            const status = Number(response.status) || 200
            const msg = response.data.msg || errorCode[status] || errorCode['default']

            if (!response.headers.notLoading) {
                const configStore = useConfigStore()
                configStore.updateRequestLoading(-1)

                if (response.data.code !== 200) {
                    configStore.clearRequestLoading()
                }
            }

            if (response.data.code === 401) {
                removeCookie('token')
                await confirm('登录状态已过期，请重新登录', '系统提示')
                return Promise.reject(new Error('登录状态已过期，请重新登录'))

                //     .then(() => {
                //         // 刷新登录页面，避免多次弹框
                //         window.location.reload()
                //     })
            }
            if (status !== 200 || response.data.code == 500) {
                message.error(msg)
                return Promise.reject(new Error(msg || 'Error'))
            }
            // 文件流获取接口返回 response.data
            if (typeof response.data !== 'object') {
                return response.data
            }
            if (!Reflect.has(response.data, 'data')) {
                return response.data
            }
            return response.data.data
        },
        (error: any) => {
            console.log(111, error)
            // const user = useUserStore()
            const status = Number(error.response.status)
            const message = error.response.data.msg || errorCode[status] || '系统错误'
            // 限制错误信息只弹出一次
            if (messageInstance) return
            messageInstance = message
            setTimeout(() => {
                messageInstance = null
            }, 1500)
            // 错误时清除loading
            const configStore = useConfigStore()
            configStore.clearRequestLoading()

            message({
                message: message,
                type: 'error'
            })
            // 后台定义 424 针对令牌过去的特殊响应码
            // if (status === 424) {
            //     ElMessageBox.alert(
            //         '登录状态已过期，请点击重新登录',
            //         '系统提示',
            //         {
            //             confirmButtonText: '重新登录',
            //             type: 'warning',
            //             callback: async () => {
            //                 try {
            //                     await user.logout()
            //                 } catch (err) {
            //                     console.log(err)
            //                 }
            //                 // 刷新登录页面，避免多次弹框
            //                 window.location.reload()

            //                 router.push({
            //                     path: '/login'
            //                 })
            //             }
            //         }
            //     )
            //     return
            // } else {
            //     ElMessage({
            //         message: message,
            //         type: 'error'
            //     })
            // }
            return Promise.reject(new Error(error))
        }
    )
    return service
}
const request = createRequest(import.meta.env.VITE_APP_BASE_API)
export default request

// async get(
//     url: string,
//     config?: AxiosRequestConfig<any>,
//     format?: {
//         labelKey: string
//         valueKey: string
//     }
// ) {
//     const data = await request.get(url, config)
//     if (format) {
//         const labelKeyReg = new RegExp(`"(${format.labelKey})"`)
//         const valueKeyReg = new RegExp(`"(${format.valueKey})"`)
//         return JSON.parse(
//             JSON.stringify(data)
//                 .replace(labelKeyReg, "label")
//                 .replace(valueKeyReg, "value")
//         )
//     }
//     return data
// }
